package com.fa4j.common.flyway.config;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.output.CleanResult;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.boot.autoconfigure.flyway.FlywayProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

@Slf4j
@AutoConfiguration
@ConditionalOnBooleanProperty(name = "spring.flyway.enabled", matchIfMissing = true)
public class CommonFlywayAutoConfiguration {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
//    @ConditionalOnBean(Flyway.class)
    public FlywayMigrationInitializer flywayInitializer(Flyway flyway,
                                                        ObjectProvider<FlywayMigrationStrategy> migrationStrategy,
                                                        FlywayProperties flywayProperties
    ) {
        if (!flywayProperties.isCleanDisabled()) {
            CleanResult result = flyway.clean();
            log.info("Flyway clean flywayVersion:{}", result.flywayVersion);
            log.info("Flyway clean cleaned:{}", result.schemasCleaned);
            log.info("Flyway clean dropped:{}", result.schemasDropped);
        }
        return new FlywayMigrationInitializer(flyway, migrationStrategy.getIfAvailable());
    }
}
